package leetcode_801_900;

import java.util.Arrays;
import java.util.Random;

public class LeeCode_885 {
    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(spiralMatrixIII(1, 4, 0, 0)));
    }
    private static int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        int remain = rows * cols, index = 1, len = 1, i = rStart, j = cStart;
        int[][] ans = new int[remain][2];
        ans[0][0] = rStart;
        ans[0][1] = cStart;
        boolean dir = true;
        while (index < ans.length){
            if (dir){
                for (int k = 0; k < len; k++) {
                    j++;
                    if (index < ans.length && i >= 0 && i < rows && j >= 0 && j < cols){
                        ans[index][0] = i;
                        ans[index][1] = j;
                        index++;
                    }
                }
                for (int k = 0; k < len; k++) {
                    i++;
                    if (index < ans.length && i >= 0 && i < rows && j >= 0 && j < cols){
                        ans[index][0] = i;
                        ans[index][1] = j;
                        index++;
                    }
                }
                len++;
                dir = false;
            }else {
                for (int k = 0; k < len; k++) {
                    j--;
                    if (index < ans.length && i >= 0 && i < rows && j >= 0 && j < cols){
                        ans[index][0] = i;
                        ans[index][1] = j;
                        index++;
                    }
                }
                for (int k = 0; k < len; k++) {
                    i--;
                    if (index < ans.length && i >= 0 && i < rows && j >= 0 && j < cols){
                        ans[index][0] = i;
                        ans[index][1] = j;
                        index++;
                    }
                }
                len++;
                dir = true;
            }
        }
        return ans;
    }
}
